<template>
  <div class="it-picker-years">
    <div class="month-picker-popover-header">
      <span class="month-picker-prev" @click="changeYear(-10)">‹</span>
      <span class="month-picker-info">{{ startYear }}-{{ endYear }}</span>
      <span class="month-picker-next" @click="changeYear(10)">›</span>
    </div>
    <div class="month-picker-popover-content">
      <div class="month-picker-years">
        <div
          v-for="(row, i) in years"
          :key="`${row}-${i}`"
          class="month-picker-years-row"
        >
          <div
            v-for="(cell, j) in row"
            :key="`${cell}-${j}`"
            class="month-picker-years-cell"
            :class="yearClasses(cell)"
            @click="onClickYear(cell)"
          >
            {{ cell }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { toMatrix } from '../datepicker/util'
import { cloneDate, getYearMonthDay } from '../datepicker/date'
import { ref, computed } from 'vue'

const props = defineProps({
  formatDate: {
    type: [Object, String],
    default: null,
  },
})
const tempValue = ref(props.formatDate)

const startYear = computed(() => {
  // const _year = tempValue.value.split(' ')[0]
  const [year] = getYearMonthDay(tempValue.value)
  return year - (year % 10) + 1
})

const endYear = computed(() => {
  return new Date().getFullYear()
})
const years = computed(() => {
  const arr = []
  for (let i = startYear.value; i <= endYear.value; i++) {
    arr.push(i)
  }
  return toMatrix(arr, 4)
})

const changeYear = (value) => {
  return
}

const emits = defineEmits(['picker-change'])
const onClickYear = (year) => {
  // const _year = tempValue.value.split(' ')[0]
  const [, month, day] = getYearMonthDay(tempValue.value)
  emits('picker-change', { value: new Date(year, month, day) })
}
const yearClasses = (year) => {
  return {
    active: isSameYear(year),
    current: isCurrentYear(year),
  }
}
const isCurrentYear = (year) => {
  const [year2] = getYearMonthDay(new Date())
  return year === year2
}
const isSameYear = (year) => {
  const [year2] = getYearMonthDay(props.formatDate)
  return year === year2
}
</script>

<style scoped>
@import url('./month-picker.css');
</style>
